package com.mywork.test;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.SimpleTypeConverter;
import org.springframework.beans.propertyeditors.CustomNumberEditor;

import java.math.BigDecimal;
import java.text.DecimalFormat;

public class Main {
    public static void main(String[] args) {
        // 创建源对象 A
        A a = new A();
        a.setAge(30);
        a.setName("John");

        // 创建目标对象 B
        B b = new B();

        // 自定义属性编辑器
        SimpleTypeConverter typeConverter = new SimpleTypeConverter();
        typeConverter.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, new DecimalFormat("#.##"), true));

        // 复制属性
        BeanUtils.copyProperties(a, b);
        b.setAge(typeConverter.convertIfNecessary(a.getAge(), BigDecimal.class));
        b.setName(a.getName());

        // 输出结果
        System.out.println("A.age: " + a.getAge());     // 30
        System.out.println("A.name: " + a.getName());   // John
        System.out.println("B.age: " + b.getAge());     // 30 (as BigDecimal)
        System.out.println("B.name: " + b.getName());   // John
    }

    static class A {
        private int age;
        private String name;

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    static class B {
        private BigDecimal age;
        private String name;

        public BigDecimal getAge() {
            return age;
        }

        public void setAge(BigDecimal age) {
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
